//
//  Record_VC.m
//  Run
//
//  Created by BetaTheta on 16/4/1.
//  Copyright © 2016年 BetaTheta. All rights reserved.
//

#import "Record_VC.h"
#import "RecordView.h"
#import "RecordTableViewCell.h"
#import "RecordDetail_VC.h"
#import "RunData.h"

@interface Record_VC ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) RecordView *recordView;

// coreData
@property (nonatomic, strong) CoreDataManager *coreDataManager;
@property (nonatomic, strong) NSMutableArray *coreDataArr;
@property (nonatomic, assign) CGFloat distance;


@end

@implementation Record_VC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"记录";
    self.view.backgroundColor = [UIColor redColor];
    
    self.coreDataManager = [CoreDataManager shareCoreDataManager];
    self.coreDataArr = [NSMutableArray arrayWithCapacity:0];
    
    [self createRecordView];
    [self createTableView];
    
}

#pragma mark - 运动记录页面
- (void)createRecordView {
    
    self.recordView = [[RecordView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height * 0.3)];
    
    [self.view addSubview:self.recordView];
    
    
}


#pragma mark - tableView
- (void)createTableView {
    
    [self getAllRunData];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.recordView.frame.size.height, self.view.frame.size.width, self.view.bounds.size.height * 0.7 - 64) style:UITableViewStylePlain];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.tableView registerClass:[RecordTableViewCell class] forCellReuseIdentifier:@"Record"];
    
    [self.view addSubview:self.tableView];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.coreDataArr.count > 0) {
        return self.coreDataArr.count;
    }
    
    return 0;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    RecordTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Record"];
    
    RunData *data = self.coreDataArr[indexPath.row];

    cell.distance.text = [NSString stringWithFormat:@"%.2fKM", data.distance.doubleValue / 1000.0];
    
    cell.time.text = [self convertTime:data.time.integerValue];
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 60;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    RecordDetail_VC *detailVC = [[RecordDetail_VC alloc] init];
    detailVC.data = self.coreDataArr[indexPath.row];
    
    [self.navigationController pushViewController:detailVC animated:YES];
    
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSLog(@"删除");
        RunData *data = self.coreDataArr[indexPath.row];
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *path = [paths lastObject];
        NSString *str = [NSString stringWithFormat:@"run%ld%.f%.f", data.time.integerValue, data.distance.doubleValue, data.speed.doubleValue];
        // 删除本地地图行走路线
        path = [path stringByAppendingString:[NSString stringWithFormat:@"/%ld.plist", [str hash]]];
        NSLog(@"%@", path);
        NSFileManager *manager = [NSFileManager defaultManager];
        [manager removeItemAtPath:path error:nil];
        
        [self.coreDataManager.managedObjectContext deleteObject:data];
        [self.coreDataManager saveContext];
        [self getAllRunData];
        
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
        
    }
    
    
    
}

#pragma mark - 获取数据
- (void)getAllRunData {
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"RunData" inManagedObjectContext:self.coreDataManager.managedObjectContext];
    [fetchRequest setEntity:entity];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.coreDataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"%@", error);
    } else {
        
        self.coreDataArr = [NSMutableArray arrayWithArray:fetchedObjects];
        
        if (self.coreDataArr.count > 0) {
            
            self.distance = 0;
            for (RunData *data in self.coreDataArr) {
                self.distance += data.distance.doubleValue;
            }
            
            self.recordView.totalDistance.text = [NSString stringWithFormat:@"%.2f", self.distance / 1000.0];
            self.recordView.trainTime.text = [NSString stringWithFormat:@"%ld", self.coreDataArr.count];
            
        } else {
            
            self.recordView.totalDistance.text = @"--";
            self.recordView.trainTime.text = @"--";
        }
        
    }
    
}

#pragma mark - 时间转换
- (NSString *)convertTime:(NSInteger)second {
    
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    second -= 3600 * 8;
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:second];
    [fmt setDateFormat:@"HH:mm:ss"];
    NSString *showtimeNew = [fmt stringFromDate:d];
    return showtimeNew;
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
